﻿using MainFile;
using MainPath;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace MainBuilder
{
    public static class Builder
    {
        private static string HtmlTemeplate = string.Empty;
        private static string ScriptTemeplate = string.Empty;
        private static string LinkTemeplate = string.Empty;
        static Builder() 
        {
            HtmlTemeplate = MyFile.GetFileToString(MyPath.HtmlTemplete);
            ScriptTemeplate = MyFile.GetFileToString(MyPath.ScriptTemplete);
            LinkTemeplate = MyFile.GetFileToString(MyPath.LinkTemplete);
        }

        public static string GetHtml(string solutionname,string title,string dom, string css, string script,string reference,string links) 
        {
            string linktemp = LinkTemeplate;
            linktemp += links;
            string scripttem1 = ScriptTemeplate;
            scripttem1 += reference;
            scripttem1 = GetScripts(scripttem1);
            string csstem = "<style type=\"text/css\">"+Environment.NewLine + css +Environment.NewLine +"</style>";
            string scriptem2 = "<script type=\"text/javascript\">"+Environment.NewLine+"$(window).ready(function(){" + script + "});"+Environment.NewLine+"</script>";
            string html = HtmlTemeplate;
            html = html.Replace("${title}",title);
            html = html.Replace("${body}",dom);
            string header = linktemp + Environment.NewLine + scripttem1 + Environment.NewLine + csstem + Environment.NewLine + scriptem2;
            header = MyPath.ConvertPath(header, solutionname);
            html = html.Replace("${head}",header);
            return html;
        }

        public static string GetScripts(string script) 
        {
            script = script.ToLower();
            Regex reg = new Regex(@"<script \b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<src>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);
            MatchCollection mc = reg.Matches(script);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach ( Match item in mc)
            {
                string src = item.Groups["src"].Value;
                if (!dic.ContainsKey(src)) 
                {
                    dic.Add(src, "");
                }
            }
            StringBuilder sb = new StringBuilder();
            foreach (string item in dic.Keys)
            {
                sb.Append("<script src=\""+item+"\" type=\"text/javascript\"></script>");
            }
            return sb.ToString();
        }
    }
}
